/// 基础响应模型
class BaseResponse<T> {
  final int code;
  final String message;
  final T? data;
  final bool success;

  BaseResponse({
    required this.code,
    required this.message,
    this.data,
    required this.success,
  });

  factory BaseResponse.fromJson(
      Map<String, dynamic> json,
      T Function(Map<String, dynamic> json)? fromJsonT,
      ) {
    return BaseResponse(
      code: json['code'] ?? 0,
      message: json['message'] ?? json['msg'] ?? 'Unknown message',
      data: fromJsonT != null && json['data'] != null
          ? fromJsonT(json['data'])
          : null,
      success: json['success'] ?? (json['code'] == 0 || json['code'] == 200),
    );
  }

  Map<String, dynamic> toJson() {
    return {
      'code': code,
      'message': message,
      'data': data,
      'success': success,
    };
  }
}

/// 分页响应模型
class PaginationResponse<T> {
  final int total;
  final int page;
  final int pageSize;
  final int totalPages;
  final List<T> list;

  PaginationResponse({
    required this.total,
    required this.page,
    required this.pageSize,
    required this.totalPages,
    required this.list,
  });

  factory PaginationResponse.fromJson(
      Map<String, dynamic> json,
      T Function(Map<String, dynamic> json) fromJsonT,
      ) {
    return PaginationResponse(
      total: json['total'] ?? 0,
      page: json['page'] ?? json['current'] ?? 1,
      pageSize: json['pageSize'] ?? json['size'] ?? 10,
      totalPages: json['totalPages'] ?? 
          (json['total'] != null && json['pageSize'] != null
              ? (json['total'] / json['pageSize']).ceil()
              : 0),
      list: (json['list'] as List<dynamic>?)?.map((e) => fromJsonT(e as Map<String, dynamic>)).toList() ?? [],
    );
  }

  Map<String, dynamic> toJson() {
    return {
      'total': total,
      'page': page,
      'pageSize': pageSize,
      'totalPages': totalPages,
      'list': list,
    };
  }
}

/// 基础请求参数模型
class BaseRequest {
  Map<String, dynamic> toJson() => {};
}

/// 分页请求参数模型
class PaginationRequest extends BaseRequest {
  final int page;
  final int pageSize;
  final String? sortBy;
  final String? orderBy; // 'asc' or 'desc'

  PaginationRequest({
    this.page = 1,
    this.pageSize = 10,
    this.sortBy,
    this.orderBy,
  });

  @override
  Map<String, dynamic> toJson() {
    return {
      'page': page,
      'pageSize': pageSize,
      if (sortBy != null) 'sortBy': sortBy,
      if (orderBy != null) 'orderBy': orderBy,
    };
  }
}

/// 上传文件请求模型
class UploadFileRequest extends BaseRequest {
  final String filePath;
  final String? fileName;
  final String? fileKey;
  final Map<String, dynamic>? extraData;

  UploadFileRequest({
    required this.filePath,
    this.fileName,
    this.fileKey = 'file',
    this.extraData,
  });

  @override
  Map<String, dynamic> toJson() {
    return {
      ...?extraData,
    };
  }
}